/*
* @Author: Administrator
* @Date:   2017-12-23 15:54:49
* @Last Modified by:   Administrator
* @Last Modified time: 2017-12-23 16:03:35
*/
import { observable, action } from 'mobx'
import { get } from '../util/comm'
import { newsListUrl } from '../util/constant';

const objToStrMap = (obj) => {
  const strMap = new Map();
  for (let k of Object.keys(obj)) { //eslint-disable-line
    strMap.set(k, obj[k]);
  }
  return strMap;
}
class MobileNewsList {
  // 新闻分类页面的新闻数据
  @observable newsList
  @observable total = 0
  @observable isLoading = false
  constructor(initialState) {
    if (initialState && initialState.mobileNewsList) {
      if (initialState.mobileNewsList.newsList) {
        this.newsList = objToStrMap(initialState.mobileNewsList.newsList)
      } else {
        this.newsList = new Map()
      }
    } else {
      this.newsList = new Map()
    }
  }
  @action getMobileListNews(channel, num, page = 1) {
    return new Promise((resolve, reject) => {
      const key = `${decodeURIComponent(channel)}${page}`
      if (!this.newsList.get(key)) {
        const baseUrl = newsListUrl;
        const params = {
          channel,
          page,
          num,
        }
        get(baseUrl, params).then((result) => {
          if (result.status === 200 && result.data.code === 1) {
            if (result.data.data.length) {
              this.newsList.set(key, result.data)
            }
            this.total = result.data.total
            resolve()
          } else {
            reject(result.data)
          }
        }).catch(reject)
      } else {
        resolve()
      }
    })
  }
  @action refresh(channel, num, page) {
    for (let i = 1; i <= page; i += 1) {
      const key = `${decodeURIComponent(channel)}${i}`
      this.newsList.delete(key)
    }
    this.getMobileListNews(channel, num, 1)
  }
}

export default MobileNewsList
